//初始化websocket
$(document).ready(function() {
    //创建socket
    var websocket;
    function createWebsocket() {
    	var token = $('#token').val();
    	if ('WebSocket' in window) {
    		websocket = new WebSocket("ws://127.0.0.1:6666/ws?token="+token);
    	} else if ('MozWebSocket' in window) {
    		websocket = new MozWebSocket("ws://127.0.0.1:6666/ws?token="+token);
    	} else {
    		websocket = new SockJS("http://127.0.0.1:6666/ws?token="+token);
    	}
    	
        websocket.onopen = function(event) {
//        	initUsers();
    		console.log("WebSocket:已连接");
    	};
    	
    	websocket.onmessage = function(ev) {
    		console.log("onmessage："+ev.data);
    		var obj=JSON.parse(ev.data);
    		if(!obj || obj == undefined) {
    			return false;
    		}
    		
    		var users = obj.to;
    		var from = obj.from;
    		var curName = $("#curName").text();
    		if(!!obj.message && from.code != curName) {//如果空消息不予处理
				 var str='';
		    		str+='<li>'+
		    				'<div class="answerHead"><img src="img/TIM图片20170926103645_04.jpg"/></div>'+
		    				'<div class="answers"><img class="jiao" src="img/TIM图片20170926103645_03_02.jpg">'+obj.message+'</div>'+
		    			'</li>';
	    		$('.newsList').append(str);
//	    		$('.conLeft').find('li.bg').children('.liRight').children('.infor').text(news);
	    		//将滚动条始终保持在底部
	    		$('.RightCont').scrollTop($('.RightCont')[0].scrollHeight );
	    		
	    		
    		}
           
            refresh(users,curName);
		};
		
		websocket.onerror = function(event) {
			console.log("WebSocket:发生错误 ");
		};
		
		websocket.onclose = function(event) {
			console.log("WebSocket:已关闭");
		}
    }
    
    //初始化WebSocket
    createWebsocket();
    
    document.onkeydown = function(a) {
        var b = document.all ? window.event: a;
        return 13 == b.keyCode ? (send(), !1) : void 0
    };
    
    $.fn.setCursorPosition = function(a) {
        return 0 == this.lengh ? this: $(this).setSelection(a, a)
    };
    
    $.fn.setSelection = function(a, b) {
        if (0 == this.lengh) return this;
        if (input = this[0], input.createTextRange) {
            var c = input.createTextRange();
            c.collapse(!0),
            c.moveEnd("character", b),
            c.moveStart("character", a),
            c.select()
        } else input.setSelectionRange && (input.focus(), input.setSelectionRange(a, b));
        return this
    };
    $.fn.focusEnd = function() {
        this.setCursorPosition(this.val().length)
    }
    
    //发送消息
    $('.sendBtn').on('click',function(){
    	var news=$('#dope').val();
    	if(news==''){
    		alert('不能为空');
    	}else{
    		$('#dope').val('');
    		
    		websocket.send(news);
    		var str='';
    		str+='<li>'+
    				'<div class="nesHead"><img src="img/TIM图片20170926103645_04.jpg"/></div>'+
    				'<div class="news"><img class="jiao" src="img/talk.jpg">'+news+'</div>'+
    			'</li>';
    		$('.newsList').append(str);
//    		setTimeout(answers,1000); 
    		$('.conLeft').find('li.bg').children('.liRight').children('.infor').text(news);
    		//将滚动条始终保持在底部
    		$('.RightCont').scrollTop($('.RightCont')[0].scrollHeight );
    	}

    });
});


//初始化用户列表
//function initUsers() {
//	var token = $('#token').val();
//	 $.get("/chat/users?token="+token, function(result){
//		 console.log(result);
//		 $("#curName").text(result.curName);
//	 });
//}

function refresh(data,curName) {
	console.log("curName="+curName);
	var h = "";
	 $.each(data, function(key, obj) {
		 console.log("obj.code="+obj.code);
		 if (curName != obj.code) {
			 h += '<li>'
	               +'<div class="liLeft"><img src="img/TIM图片20170926103645_04.jpg"/></div>'
	               +'<div class="liRight">'
	               +    '<span class="intername">'+obj.code+'</span>'
	               +	'<span class="infor">[笑脸]</span>'
	               +'</div>'
	             +'</li>';
		 }
		 
	 });
	 
	 $('#chatList ul').html("").append(h);
}


//获取好友网名
$('#chatList ul').on('click','li',function(){
	$(this).addClass('bg').siblings().removeClass('bg');
	var intername=$(this).children('.liRight').children('.intername').text();
	$('.headName').text(intername);
	$('.newsList').html('');
})


// 随机产生一条回复
function answers() {
	var arr = [ "你好", "今天天气很棒啊", "你吃饭了吗？", "我最美我最美", "我是可爱的僵小鱼", "你们忍心这样子对我吗？",
			"spring天下无敌，实习工资850", "我不管，我最帅，我是你们的小可爱", "段友出征，寸草不生",
			"一入段子深似海，从此节操是路人", "馒头：嗷", "突然想开个车：www.jq22.com",
			"段子界混的最惨的两个狗：拉斯，普拉达。。。", "<img src='img/15.gif'>",
			"<img src='img/13.gif'>", "<img src='img/9.gif'>",
			"<img src='img/25.gif'>", "<img src='img/38.gif'>",
			"<img src='img/46.gif'>", "<img src='img/51.gif'>",
			"<img src='img/68.gif'>", "<img src='img/38.gif'>",
			"<img src='img/84.gif'>", "<img src='img/33.gif'>",
			"<img src='img/66.gif'>", "<img src='img/22.gif'>",
			"<img src='img/16.gif'>", "<img src='img/86.gif'>",
			"<img src='img/91.gif'>", "<img src='img/73.gif'>",
			"<img src='img/49.gif'>" ];
	var aa = Math.floor((Math.random() * arr.length));
	var answer = '';
	answer += '<li>'
			+ '<div class="answerHead"><img src="img/tou.jpg"/></div>'
			+ '<div class="answers"><img class="jiao" src="img/TIM图片20170926103645_03_02.jpg">'
			+ arr[aa] + '</div>' + '</li>';
	$('.newsList').append(answer);
	$('.RightCont').scrollTop($('.RightCont')[0].scrollHeight);
	// 历史消息的展现与隐藏
	var newlen = $('.newsList li').length;
	var lis = $('.newsList li:last').index();
	var maxlen = newlen - 5;
	console.log(lis);
	if (newlen % 10 > 5) {
		$('.ChatRecord').show();
		$('.newsList li:lt(' + maxlen + ')').hide();
	}
}
//表情包的展现与隐藏
$('.ExP').on('click',function(){
	if($('.emjon').css('display')=='none'){
		$('.emjon').show();
	}else{
		$('.emjon').hide();
	}
})
	
//发送表情
$('.emjon li').on('click',function(){
	var imgSrc=$(this).children('img').attr('src');
	var str="";
	str+='<li>'+
			'<div class="nesHead"><img src="img/6.jpg"/></div>'+
			'<div class="news"><img class="jiao" src="img/talk.jpg"><img class="Expr" src="'+imgSrc+'"></div>'+
		'</li>';
	$('.newsList').append(str);
	setTimeout(answers,1000);
	$('.emjon').hide();
	$('.RightCont').scrollTop($('.RightCont')[0].scrollHeight );
})

//展开历史消息
$('.RightCont').on('click','.ChatRecord',function(){
	$('.newsList li:eq(0),li:gt(0)').show();
	$('.ChatRecord').hide();
})
	
	